//
//  GetParks.m
//  HundPark
//
//  Created by Aguilar Rolando on 2013-03-04.
//  Copyright (c) 2013 ARV IT. All rights reserved.
//


#import "City.h"
#import "DogParkClient.h"

@interface City()

@end


#define GETCITY @"HundApp.php?method=getCity"
//JSONModel
//#define GETCITY2 @"HundApp.php?method=getCity2"

#define ADDNEWPARK @"HundApp.php?method=addNewPark"
#define GETCHECKEDINCITY @"HundApp.php?method=getCheckedInCity"
#define BYET_USERNAME @"b8_12627659"
#define BYET_PASSWORD @"intisol"

@implementation City

@synthesize parks =_parks;

#pragma mark - Lazy Instantiation
// Lazy instantiation
 -(NSMutableArray *)parks
 {
     if(!_parks)
         _parks = [[NSMutableArray alloc] init];
 
	return _parks;
 }

- (id)init{
    self = [super init];
    if(self)
    {
        [self syncPlistFromDB];
    }
    return self;
}


// Returns the documents path
-(NSString *) documentsPath{
    NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    return documentsDir;
}


// Sync plist from db server
- (void)syncPlistFromDB {

    // PLIST file path
    NSString *plistFileName = [[self documentsPath] stringByAppendingString:@"/HundParkCoordinates.plist"];
        
    [[DogParkClient sharedClient] getPath:GETCITY
                               parameters:nil
                                  success:^(AFHTTPRequestOperation *operation, id responseObject) {
        // Parse json
        NSArray *results = responseObject;
        
        // WHen using JSONModel
        //[self didReceiveJson:results];
        
        // Write to plistFileName
        [results writeToFile:plistFileName atomically:YES];
        
        // delegate creeteParkFromList
        [self createParksFromPlist:plistFileName];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {        
        [self createParksFromPlist:plistFileName];

    }];
    
}

// Used for JsonModel
-(void) didReceiveJson: (NSArray *) obj
{
    NSString *plistFileName = [[self documentsPath] stringByAppendingString:@"/HundParkCoordinates.plist"];
    
    //NSArray* parksArray = obj[@"parker"];
    //self.parks = [Park arrayOfModelsFromDictionaries:obj];
    
    [obj writeToFile:plistFileName atomically:YES];
    // [self.tableView reloadData];
    [self.delegate finishedSyncPlist];
}

// Update plist
- (void)createParksFromPlist:(NSString *)plistFileName {
    // Read in PLIST
    NSMutableArray *parkFromPList = [NSMutableArray arrayWithContentsOfFile:plistFileName];
    
    // Update Parks
    for (NSDictionary *parkDic in parkFromPList) {
        
        Park *park = [[Park alloc] initWithLongitude:[parkDic[@"Longitude"] doubleValue]
                                            latitude:[parkDic[@"Latitude"] doubleValue]];
        park.name =  parkDic[@"Name"];
        park.distric = parkDic[@"Distric"];
        park.info = parkDic[@"Info"];
        park.imageName = parkDic[@"ImageName"];
        park.parkId = parkDic[@"id"];
        
        // Add park obj to global model NSArray parks
        [self.parks addObject:park];
    }
    
    // Delegate that it has finished syncing
    [self.delegate finishedSyncPlist];
}



// Sorts the parks acoording to current position 
- (void)sortArray:(CLLocation *)currentLocation;
{
    NSMutableArray *sortedParks = [[NSMutableArray alloc]init];
    // Set distance for each park from current position
    for (Park *park in self.parks)
    {
        CLLocation *targetPark = [[CLLocation alloc]initWithLatitude:park.coordinate.latitude
                                                           longitude:park.coordinate.longitude];
        CLLocationDistance distance = [targetPark distanceFromLocation:currentLocation];
        
        park.distance = distance;
        [sortedParks addObject:park];
    }
    
    // Sort array with distance attribute
    NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc] initWithKey:@"distance"
                                                                    ascending:YES];
    NSArray *descriptors = [NSArray arrayWithObject:valueDescriptor];
    NSArray *sortedArray = [sortedParks sortedArrayUsingDescriptors:descriptors];
	
    self.parks = [(NSArray*)sortedArray mutableCopy];
}

// Save new park in db
- (void)saveParkInDB:(Park *)newPark newImage:(UIImage *)parkImage
{
    // Create Park dictionary to send
    NSDictionary *newParkDic = @{@"name": newPark.name,
                                 @"distric": newPark.distric,
                                 @"latitude":[[NSNumber numberWithDouble:newPark.coordinate.latitude] stringValue],
                                 @"longitude":[[NSNumber numberWithDouble:newPark.coordinate.longitude] stringValue],
                                 @"info":newPark.info,
                                 @"imageName":newPark.imageName};
    
    // Prepare Image
    NSData *imageData = UIImagePNGRepresentation(parkImage);
    
    DogParkClient* httpClient = [DogParkClient sharedClient];
    
    [httpClient setAuthorizationHeaderWithUsername:BYET_USERNAME password:BYET_PASSWORD];
    
    NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST"
                                                                         path:ADDNEWPARK
                                                                   parameters:newParkDic
                                                    constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"parkPhoto" mimeType:@"image/png"];
    }];
    
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
                                                                                        success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        // Parse json
        NSLog(@"%@",JSON);
        NSArray *results = JSON;
        
        // TODO: Result is array with one object. Fix in server side
        for(NSDictionary *parkIdDic in results)
        {
            newPark.parkId = parkIdDic[@"id"];
           
        }
        
        // Delegate that it has finished added new park in DB
        [self.delegate finishedSavingParkInDB:newPark];
        
        // Moved to saveImageFileServer
        [self.parks removeAllObjects];
        [self syncPlistFromDB];
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSString *errorDescription = [NSString stringWithFormat:@"Request Failed with Error: %@, %@", error, error.userInfo];
        
        UIAlertView *errorAlert = [[UIAlertView alloc]
                                   initWithTitle:@"Hundpark"
                                   message:errorDescription
                                   delegate:nil
                                   cancelButtonTitle:@"OK"
                                   otherButtonTitles:nil];
        [errorAlert show];
    }];
    [operation start];

}

-(void)getAmountOfVisitors
{
    [[DogParkClient sharedClient] getPath:GETCHECKEDINCITY
                               parameters:nil
                                  success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        // Parse json
        NSArray *results = responseObject;
        
        // Updated parks array with retrived JSON
        for (Park *park in self.parks)
        {
            for (NSDictionary *dict in results) {
                
                // Get parkId and get value off checked in visitors in json answer
                if([park.parkId isEqualToString:dict[@"id"]])
                {
                    park.amountOfDogs = dict[@"amountOfVisitors"];
                }
            }
            
        }
        // Delegate that it has finished syncing
        [self.delegate finishedGetAmountOfVisitors];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {        
        NSString *errorDescription = [NSString stringWithFormat:@"Request Failed with Error: %@, %@", error, error.userInfo];
         
         UIAlertView *errorAlert = [[UIAlertView alloc]
                                    initWithTitle:@"Hundpark"
                                    message:errorDescription
                                    delegate:nil
                                    cancelButtonTitle:@"OK"
                                    otherButtonTitles:nil];
         [errorAlert show];
        
    }];
}


@end

